package cuong.ptit.androidvn;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import cuong.ptit.andoridvn.R;
import cuong.ptit.androidvn.helper.Function;
import cuong.ptit.androidvn.helper.JSONParser;
import cuong.ptit.androidvn.widget.PullAndLoadListView;
import cuong.ptit.androidvn.widget.PullAndLoadListView.OnLoadMoreListener;
import cuong.ptit.androidvn.widget.PullToRefreshListView.OnRefreshListener;

/*
 * @author LeCuong 
 * @version 1.0
 */

public class GetThreadJoin extends ListActivity {
	private ProgressDialog pDialog;
	private String user_name, user_id, hash_user, all_post;
	private int loadcount = 10;
	private int load = 0;
	private int loadindex = 0;
	private int max = 0, max2 = 0;
	private int sizeid;// count item list_idthread
	private JSONParser jsonParser = new JSONParser();

	// array list
	private ArrayList<HashMap<String, String>> list_idthread;
	private ArrayList<HashMap<String, String>> list_thread;
	private ArrayList<HashMap<String, String>> list_box;
	private ArrayList<HashMap<String, String>> list_comment;

	// json----------------------------------------
	// json all post
	private static final String url_post = "http://android.vn/api.php?action=getPosts&hash=d8e8fca2dc0f896fd7cb4cb0031ba249&order_by=post_date";
	private static final String TAG_ID_THREAD = "thread_id";

	// json info user
	private final static String url_user = "http://android.vn/api.php?action=getUser";
	private final static String TAG_MESSAGE = "message_count";

	// json comment last post
	private final static String url_comment = "http://android.vn/api.php?action=getPosts&order_by=post_id&limit=1";
	private final static String TAG_COMMENT = "message";

	// json name box
	private final static String url_box = "http://android.vn/api.php?action=getNodes&hash=d8e8fca2dc0f896fd7cb4cb0031ba249&node_type=forum";
	private final static String TAG_NAME_BOX = "title";
	// json info thread
	private static final String url_info_thread = "http://android.vn/api.php?action=getThread";
	private static final String TAG_ID_NODE = "node_id";
	private static final String TAG_TITLE = "title";
	private static final String TAG_DATE = "last_post_date";
	private static final String TAG_LAST_USER = "last_post_username";
	private static final String TAG_VIEW = "view_count";
	private static final String TAG_REPLY = "reply_count";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_category);

		Intent i = getIntent();
		user_name = i.getStringExtra("user_name");
		user_id = i.getStringExtra("user_idname");
		String has = i.getStringExtra("user_hash");
		hash_user = user_name + ":" + has;

		new LoadThread().execute();

		((PullAndLoadListView) getListView())
				.setOnRefreshListener(new OnRefreshListener() {

					@Override
					public void onRefresh() {

						new RefreshThread().execute();

					}
				});

		((PullAndLoadListView) getListView())
				.setOnLoadMoreListener(new OnLoadMoreListener() {

					@Override
					public void onLoadMore() {
						load++;// moi lan load tang len 1
						loadcount = loadcount + 10;
						loadindex = list_thread.size();
						new LoadMoreThread().execute();

					}
				});

	}

	class LoadThread extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(GetThreadJoin.this);
			pDialog.setMessage("Loading...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {

			// get all post comment user------------------------------------
			List<NameValuePair> paramsNumMess = new ArrayList<NameValuePair>();
			paramsNumMess.add(new BasicNameValuePair("hash", hash_user));
			String json_user = jsonParser.makeHttpRequest(url_user, "GET",
					paramsNumMess);

			try {
				JSONObject p = new JSONObject(json_user);
				if (p != null) {
					all_post = p.getString(TAG_MESSAGE);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			// get all id thread---------------------------------------------
			list_idthread = new ArrayList<HashMap<String, String>>();
			List<NameValuePair> paramsIdthread = new ArrayList<NameValuePair>();
			paramsIdthread.add(new BasicNameValuePair("author", user_id));
			paramsIdthread.add(new BasicNameValuePair("limit", all_post));
			String json_idthread = jsonParser.makeHttpRequest(url_post, "GET",
					paramsIdthread);
			try {
				JSONObject posts_all = new JSONObject(json_idthread);
				JSONObject postall = posts_all.getJSONObject("posts");

				Iterator<?> keys_all = postall.keys();

				while (keys_all.hasNext()) {
					String key = (String) keys_all.next();

					JSONObject c = postall.getJSONObject(key);
					String id_thread = c.getString(TAG_ID_THREAD);

					HashMap<String, String> map = new HashMap<String, String>();
					map.put(TAG_ID_THREAD, id_thread);

					list_idthread.add(map);

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			Function.RemoreItemRepeatArray(list_idthread);

			// get all name box------------------------------------------------
			list_box = new ArrayList<HashMap<String, String>>();
			List<NameValuePair> parmas_forum = new ArrayList<NameValuePair>();
			String jsonForum = jsonParser.makeHttpRequest(url_box, "GET",
					parmas_forum);

			try {

				JSONObject forums = new JSONObject(jsonForum);
				JSONObject forum = forums.getJSONObject("nodes");

				Iterator<?> keysf = forum.keys();

				while (keysf.hasNext()) {
					String key = (String) keysf.next();
					JSONObject c = forum.getJSONObject(key);

					String id_node = c.getString(TAG_ID_NODE);
					String title_node = c.getString(TAG_NAME_BOX);

					HashMap<String, String> map = new HashMap<String, String>();
					map.put(TAG_ID_NODE, id_node);
					map.put(TAG_NAME_BOX, title_node);

					list_box.add(map);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			// check item ---------------------
			if (list_idthread.size() < 10) {
				max = list_idthread.size();
			} else if (list_idthread.size() > 10) {
				max = 10;
			} else if (list_idthread.size() == 0) {
				max = 0;
			}

			// get all comment last thread----------------------------

			list_comment = new ArrayList<HashMap<String, String>>();
			// get thread ------------------------------------------------------

			list_thread = new ArrayList<HashMap<String, String>>();
			String value = "";

			for (int i = 0; i < max; i++) {
				HashMap<String, String> map = list_idthread.get(i);
				value = map.get("thread_id");

				// get comment last thread-------------------

				// get comment
				List<NameValuePair> params_cm = new ArrayList<NameValuePair>();
				params_cm.add(new BasicNameValuePair("thread_id", value));
				String json_cm = jsonParser.makeHttpRequest(url_comment, "GET",
						params_cm);
				try {
					JSONObject cms = new JSONObject(json_cm);
					JSONObject cm = cms.getJSONObject("posts");

					Iterator<?> keys = cm.keys();

					while (keys.hasNext()) {
						String key = (String) keys.next();
						JSONObject c = cm.getJSONObject(key);
						String id = c.getString("thread_id");
						String cmt = c.getString("message");

						HashMap<String, String> mapc = new HashMap<String, String>();
						mapc.put("thread_id", id);
						mapc.put("message", cmt);

						list_comment.add(mapc);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

				// get title,id_node,id_thread, last post username,view,reply

				List<NameValuePair> params_thread = new ArrayList<NameValuePair>();
				params_thread.add(new BasicNameValuePair("hash", hash_user));
				params_thread.add(new BasicNameValuePair("value", value));

				String jsontitle = jsonParser.makeHttpRequest(url_info_thread,
						"GET", params_thread);

				try {
					JSONObject a = new JSONObject(jsontitle);
					if (a != null) {
						String id_thread = a.getString(TAG_ID_THREAD);
						String title = a.getString(TAG_TITLE);
						String id_node = a.getString(TAG_ID_NODE);
						String date = a.getString(TAG_DATE);
						String user = a.getString(TAG_LAST_USER);
						String view = a.getString(TAG_VIEW);
						String reply = a.getString(TAG_REPLY);

						String box = Function.GetNameBox(list_box, id_node);

						/*
						 * String comment = Function.GetComment(list_comment,
						 * id_thread);
						 */
						// String comment = Function.getFrist10Word(comment1);
						// Log.d("cm", comment);

						HashMap<String, String> mapp = new HashMap<String, String>();
						// mapp.put(TAG_ID_THREAD, id_thread);
						mapp.put(TAG_TITLE, title);
						mapp.put(TAG_DATE, date);
						mapp.put(TAG_LAST_USER, user);
						mapp.put(TAG_VIEW, view);
						mapp.put(TAG_REPLY, reply);
						mapp.put("namebox", box);
						// mapp.put("comment", comment);

						list_thread.add(mapp);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

			}

			// check log--------------------------------------------------------
			// Log.d("message", all_post);
			// Log.d("list thread ", "size=" + list_thread);
			// Log.d("list forum", "size=" + list_box.size());
			Log.d("list commnent", ">" + list_comment);

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			pDialog.dismiss();

			runOnUiThread(new Runnable() {
				public void run() {

					ListAdapter adapter = new SimpleAdapter(
							GetThreadJoin.this,
							list_thread,
							R.layout.list_item_get_thread_join,
							new String[] { TAG_LAST_USER, TAG_VIEW, TAG_REPLY,
									TAG_DATE, TAG_TITLE, "namebox", "comment" },
							new int[] { R.id.tv_user_getThreadUser,
									R.id.tv_view_getThreadUser,
									R.id.tv_post_getThreadUser,
									R.id.tv_date_getThreadUser,
									R.id.tv_title_getThreadUser,
									R.id.tv_box_getThreadUser,
									R.id.tv_title_getCommentThreadUser });

					setListAdapter(adapter);

				}
			});
			super.onPostExecute(result);
		}
	}

	class LoadMoreThread extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {

			if (isCancelled()) {
				return null;
			}

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}

			// check loadmore--------------------------
			sizeid = list_idthread.size();

			if (loadcount < sizeid) {
				if (sizeid - loadcount > 10) {
					max2 = max + 10;
				} else if (sizeid - loadcount < 10) {
					max2 = (sizeid - loadcount) + loadindex;
				}

				// ??????????????????????????????
			} else if (loadcount > sizeid) {
				if (load == 1) {
					max2 = (sizeid - 10) + max;
				} else if (load > 1) {
					max2 = max2+0;
				}

			} else if (loadcount == sizeid) {
				max2 = max;
			}
			
			Log.d("MAX2", ">"+max2);
			for (int i = loadindex; i < max2; i++) {
				HashMap<String, String> map = list_idthread.get(i);
				String value = map.get("thread_id");

				// load---------------------

				// get comment
				List<NameValuePair> params_cm = new ArrayList<NameValuePair>();
				params_cm.add(new BasicNameValuePair("thread_id", value));
				String json_cm = jsonParser.makeHttpRequest(url_comment, "GET",
						params_cm);
				try {
					JSONObject cms = new JSONObject(json_cm);
					JSONObject cm = cms.getJSONObject("posts");

					Iterator<?> keys = cm.keys();

					while (keys.hasNext()) {
						String key = (String) keys.next();
						JSONObject c = cm.getJSONObject(key);
						String id = c.getString("thread_id");
						String cmt = c.getString("message");

						HashMap<String, String> mapc = new HashMap<String, String>();
						mapc.put("thread_id", id);
						mapc.put("message", cmt);

						list_comment.add(mapc);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

				// get title,id_node,id_thread, last post username,view,reply

				List<NameValuePair> params_thread = new ArrayList<NameValuePair>();
				params_thread.add(new BasicNameValuePair("hash", hash_user));
				params_thread.add(new BasicNameValuePair("value", value));

				String jsontitle = jsonParser.makeHttpRequest(url_info_thread,
						"GET", params_thread);

				try {
					JSONObject a = new JSONObject(jsontitle);
					if (a != null) {
						String id_thread = a.getString(TAG_ID_THREAD);
						String title = a.getString(TAG_TITLE);
						String id_node = a.getString(TAG_ID_NODE);
						String date = a.getString(TAG_DATE);
						String user = a.getString(TAG_LAST_USER);
						String view = a.getString(TAG_VIEW);
						String reply = a.getString(TAG_REPLY);

						String box = Function.GetNameBox(list_box, id_node);

						/*
						 * String comment = Function.GetComment(list_comment,
						 * id_thread);
						 */
						// String comment = Function.getFrist10Word(comment1);
						// Log.d("cm", comment);

						HashMap<String, String> mapp = new HashMap<String, String>();
						// mapp.put(TAG_ID_THREAD, id_thread);
						mapp.put(TAG_TITLE, title);
						mapp.put(TAG_DATE, date);
						mapp.put(TAG_LAST_USER, user);
						mapp.put(TAG_VIEW, view);
						mapp.put(TAG_REPLY, reply);
						mapp.put("namebox", box);
						// mapp.put("comment", comment);

						list_thread.add(mapp);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

				Log.d("thread id", value + "max=" + max2);
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			((BaseAdapter) getListAdapter()).notifyDataSetChanged();
			((PullAndLoadListView) getListView()).onLoadMoreComplete();
			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled(String result) {
			((PullAndLoadListView) getListView()).onLoadMoreComplete();
			super.onCancelled(result);
		}

	}

	class RefreshThread extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {

			if (isCancelled()) {
				return null;
			}

			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
			}

			list_thread.clear();
			// list_thread = new ArrayList<HashMap<String, String>>();

			// refresh list view--------------------------
			if (list_idthread.size() < 10) {
				max = list_idthread.size();
			} else if (list_idthread.size() > 10) {
				max = 10;
			} else if (list_idthread.size() == 0) {
				max = 0;
			}

			// get all comment last thread----------------------------

			list_comment = new ArrayList<HashMap<String, String>>();
			// get thread ------------------------------------------------------

			list_thread.clear();
			// list_thread = new ArrayList<HashMap<String, String>>();
			String value = "";

			for (int i = 0; i < max; i++) {
				HashMap<String, String> map = list_idthread.get(i);
				value = map.get("thread_id");

				// get comment last thread-------------------

				// get comment
				List<NameValuePair> params_cm = new ArrayList<NameValuePair>();
				params_cm.add(new BasicNameValuePair("thread_id", value));
				String json_cm = jsonParser.makeHttpRequest(url_comment, "GET",
						params_cm);
				try {
					JSONObject cms = new JSONObject(json_cm);
					JSONObject cm = cms.getJSONObject("posts");

					Iterator<?> keys = cm.keys();

					while (keys.hasNext()) {
						String key = (String) keys.next();
						JSONObject c = cm.getJSONObject(key);
						String id = c.getString("thread_id");
						String cmt = c.getString("message");

						HashMap<String, String> mapc = new HashMap<String, String>();
						mapc.put("thread_id", id);
						mapc.put("message", cmt);

						list_comment.add(mapc);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

				// get title,id_node,id_thread, last post username,view,reply

				List<NameValuePair> params_thread = new ArrayList<NameValuePair>();
				params_thread.add(new BasicNameValuePair("hash", hash_user));
				params_thread.add(new BasicNameValuePair("value", value));

				String jsontitle = jsonParser.makeHttpRequest(url_info_thread,
						"GET", params_thread);

				try {
					JSONObject a = new JSONObject(jsontitle);
					if (a != null) {
						String id_thread = a.getString(TAG_ID_THREAD);
						String title = a.getString(TAG_TITLE);
						String id_node = a.getString(TAG_ID_NODE);
						String date = a.getString(TAG_DATE);
						String user = a.getString(TAG_LAST_USER);
						String view = a.getString(TAG_VIEW);
						String reply = a.getString(TAG_REPLY);

						String box = Function.GetNameBox(list_box, id_node);

						/*
						 * String comment = Function.GetComment(list_comment,
						 * id_thread);
						 */
						// String comment = Function.getFrist10Word(comment1);
						// Log.d("cm", comment);

						HashMap<String, String> mapp = new HashMap<String, String>();
						// mapp.put(TAG_ID_THREAD, id_thread);
						mapp.put(TAG_TITLE, title);
						mapp.put(TAG_DATE, date);
						mapp.put(TAG_LAST_USER, user);
						mapp.put(TAG_VIEW, view);
						mapp.put(TAG_REPLY, reply);
						mapp.put("namebox", box);
						// mapp.put("comment", comment);

						list_thread.add(mapp);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
			load = 0;
			loadcount = 10;
			loadindex = 0;
			max = 10;
			Log.d("max load", "load=" + load + "count=" + loadcount + "index"
					+ loadindex + "max=" + max + "list" + list_thread.size());

			return null;

		}

		@Override
		protected void onPostExecute(String result) {
			((BaseAdapter) getListAdapter()).notifyDataSetChanged();
			((PullAndLoadListView) getListView()).onRefreshComplete();
			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			((PullAndLoadListView) getListView()).onRefreshComplete();
			super.onCancelled();
		}

	}
}
